package com.guli.ucenter.util;

import com.guli.ucenter.entity.Member;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

/**
 * @author helen
 * @since 2019/4/30
 */
public class JwtUtils {

    public static final String SUBJECT = "guli-user";

    //秘钥
    public static final String APPSECRET = "guli666";
    //过期时间，毫秒，30分钟

    public static final long EXPIRE = 1000 * 60 * 30;

    /**
     * 生成jwt token
     *
     * @param member
     * @return
     */
    public static String generateJWT(Member member) {

        if (member == null || StringUtils.isEmpty(member.getId())
                || StringUtils.isEmpty(member.getNickname())
                || StringUtils.isEmpty(member.getAvatar())) {
            return null;
        }
        String token = Jwts.builder()
                //设置预定义载荷
                .setSubject(SUBJECT)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .setId(UUID.randomUUID().toString())
                //设置自定义载荷
                .claim("nickname", member.getNickname())
                .claim("id", member.getId())
                .claim("avatar", member.getAvatar())
                .signWith(SignatureAlgorithm.HS256, APPSECRET).compact();

        return token;
    }

    public static Claims checkJWT(String token) {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APPSECRET).parseClaimsJws(token);
        Claims body = claimsJws.getBody();
        return body;
    }

}
